package com.hnfnu.controller;

import com.hnfnu.protocol.dto.DisburseDTO;
import com.hnfnu.protocol.dto.DonationsOrderByTimeDTO;
import com.hnfnu.protocol.dto.DonationsRecordDTO;
import com.hnfnu.protocol.dto.ResponseResult;
import com.hnfnu.entity.Disburse;
import com.hnfnu.protocol.model.bo.DisburseRecordAddRecordInputBO;
import com.hnfnu.protocol.model.bo.DisburseRecordGetRecordsByProjectIdInputBO;
import com.hnfnu.protocol.model.bo.DonationRecordAddRecordInputBO;
import com.hnfnu.protocol.model.bo.DonationRecordGetRecordsByProjectIdInputBO;
import com.hnfnu.protocol.param.DisburseParam;
import com.hnfnu.protocol.param.DisburseProgressParam;
import com.hnfnu.protocol.vo.DonationsByProjectIdVO;
import com.hnfnu.protocol.vo.ProjectDisburseProgressVO;
//import com.hnfnu.service.DisburseRecordService;
//import com.hnfnu.service.DonationRecordService;
import com.hnfnu.utils.MailUtils;
import com.hnfnu.utils.OssUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("disburse")
public class DisburseController extends BaseController {

    @Value("${spring.mail.username}")
    private String fromEmail;


//
//    @Autowired
//    private DisburseRecordService service;


    @PostMapping("/insertDisburses")
    public ResponseResult insertDisbursesProgress(@RequestParam("projectId") Integer projectId,
                                                  @RequestParam("amount") Double amount,
                                                  @RequestParam("imgFile") MultipartFile imgFile,
                                                  @RequestParam("time") Date time,
                                                  @RequestParam("description") String description,
                                                  @RequestParam("progress") String progress) throws IOException {

        Double emailAmount = amount;

        // 图片 url
        String imgFileUrl = OssUtils.upload(imgFile, "disburse");

        // 支出上链
        DisburseRecordAddRecordInputBO inputBO = new DisburseRecordAddRecordInputBO();
        inputBO.setProjectId(BigInteger.valueOf(projectId));
        inputBO.setImgUrl(imgFileUrl);
        inputBO.setDescription(description);
        inputBO.setAmount(String.valueOf(amount));
        inputBO.setRecordTime(String.valueOf(time));
        try {
//            service.addRecord(inputBO);
        } catch (Exception e) {
            return new ResponseResult(500, "支出失败");
        }


        Disburse disburse = new Disburse();
        disburse.setAmount(amount);
        disburse.setProjectId(projectId);
        disburse.setAddress(imgFileUrl);
        disburse.setDescription(description);
        disburse.setProgress(progress);

        // 给用户发邮件
        List<DonationsOrderByTimeDTO> amountAndUserIdOrderByTime = donationsService.selectAmountAndUserIdOrderByTime(projectId);
        List<Integer> userIds = new ArrayList<>();
        if (amount > 0) {
            for (DonationsOrderByTimeDTO o : amountAndUserIdOrderByTime) {
                Double userDonationAmount = o.getAmount();
                userIds.add(o.getUserId());
                donationsService.updateSpendByUserIdAndProjectId(o.getUserId(), projectId);
                amount -= userDonationAmount;
                if (amount <= 0) {
                    break;
                }
            }
        }

        String projectName = projectService.getProjectNameByProjectId(projectId);

        List<String> userEmails = userService.getEmailsByIds(userIds);
        for (String email : userEmails) {
            mailUtils = new MailUtils(mailSender, fromEmail);
            mailUtils.sendDonationsDirection(email, time, projectName, emailAmount, progress);
        }

        // 保存一份到数据库
        Boolean inserted = disburseService.insertDisburse(disburse);

        System.out.println(imgFileUrl);
        DisburseProgressParam disburseProgressParam = new DisburseProgressParam();
        disburseProgressParam.setProjectId(projectId);
        disburseProgressParam.setAddress(imgFileUrl);
        disburseProgressParam.setTime(time);
        disburseProgressParam.setDescription(description);
        disburseProgressParam.setProgress(progress);

        if (!inserted) {
            return new ResponseResult(500, "支出出错");
        }
        return new ResponseResult(200, "支出成功");
    }


    @GetMapping("/getDisburses")
    public ResponseResult getDisburses() {
        List<DisburseDTO> disbursesDTO = disburseService.getDisburses();
        return new ResponseResult(200, "支出账单", disbursesDTO);
    }


    @GetMapping("/getDisbursesByProjectId")
    public ResponseResult getDisbursesByProjectId(@Param("projectId") Integer projectId) {
        List<DisburseDTO> disburseDTOSByProjectId = disburseService.getDisbursesByProjectId(projectId);
        return new ResponseResult(200, "项目进展", disburseDTOSByProjectId);
    }

    @GetMapping("/getTotalDisburse")
    public ResponseResult getTotalDisburse() {
        Double totalDisburse = disburseService.getTotalDisburse();
        return new ResponseResult(200, "总支出", totalDisburse);
    }
}
